package com.lichunsheng.stu.realm;

import com.lichunsheng.stu.entity.PeRole;
import com.lichunsheng.stu.entity.PeUser;
import com.lichunsheng.stu.service.PePermissionService;
import com.lichunsheng.stu.service.PeRoleService;
import com.lichunsheng.stu.service.PeUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private PeUserService peUserService;
    @Autowired
    private PeRoleService peRoleService;
    @Autowired
    private PePermissionService pePermissionService;

    @Override
    public void setName(String name) {
        super.setName("myShiroRealm");
    }

    /*
     * 授权
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollecion) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

//        获取安全数据
        SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection) principalCollecion;
        PeUser userInfo = (PeUser) simplePrincipalCollection.getPrimaryPrincipal();
//        查询当前角色
        String id = userInfo.getId();
        Set<PeRole> rolesEnt = peRoleService.findByUserName(id);
        HashSet<String> roles = new HashSet<>();
        HashSet<String> permissions = new HashSet<>();
        if (!CollectionUtils.isEmpty(rolesEnt)) {

            rolesEnt.forEach(peRole -> {
                roles.add(peRole.getName());
                Set<String> permissionStrs = pePermissionService.findByRoleId(peRole.getId());
                permissions.addAll(permissionStrs);
            });
        }
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    /*
     * 认证
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        获取当前登录的用户信息
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());
        PeUser peUser = peUserService.findByUserName(username);
        if (peUser != null && password.equals(peUser.getPassword())) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(peUser, password, getName()); // 安全数据  密码  realm名字
            return info;
        }
        return null;
    }
}
